package org.jsola.hr.common;

import org.jsola.common.FileKit;
import org.jsola.hr.exception.HrException;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author wo
 */

public class Base64Kit {

    public static File base64ToFile(String base64) {
        String systemTempPath = FileKit.getSystemTempPath();
        if (systemTempPath.endsWith(File.separator)) {
            systemTempPath = systemTempPath.substring(0, systemTempPath.length() - 1);
        }
        String type = getBase64Type(base64);
        systemTempPath += "." + type;
        File file = new File(systemTempPath);
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return base64ToFile(base64, file.getPath());
    }

    /**
     * 传入base64编码字符以及保存路径
     */
    public static File base64ToFile(String base64, String filePath) {
        // base64编码字符必须不能包含base64的前缀，否则会报错
        // 移除前缀
        base64 = base64.split(",")[1];
        // filePath需要为具体到文件的名称和格式，如111.txt
        // 文件路径需要双斜杠转义，如:  D:\\files\\111.txt
        HrException.isFalse(base64 == null && filePath == null, "生成文件失败，未传入参数!");
        // 判断是否base64是否包含data:image/png;base64等前缀，如果有则去除
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes;
        try {
            bytes = decoder.decodeBuffer(base64);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for (int i = 0; i < bytes.length; ++i) {
            // 调整异常数据
            if (bytes[i] < 0) {
                bytes[i] += 256;
            }
        }
        InputStream inputStream = new ByteArrayInputStream(bytes);
        // 此处判断文件夹是否存在，不存在则创建除文件外的父级文件夹
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("上级目录" + file.getParentFile());
            file.getParentFile().mkdirs();
        }
        try (OutputStream outputStream = Files.newOutputStream(Paths.get(filePath))) {
            // 生成指定格式文件
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 判断图片base64字符串的文件格式
     */
    public static String getBase64Type(String base64) {
        String type = "";
        if (base64.contains("data:image/png;base64")) {
            base64 = base64.substring(22);
            type = "png";
            System.out.println("包含png");
        }
        if (base64.contains("data:image/jpeg;base64")) {
            base64 = base64.substring(23);
            type = "jpeg";
            System.out.println("包含jpeg");
        }
        if (base64.contains("data:application/pdf;base64")) {
            base64 = base64.substring(28);
            type = "pdf";
            System.out.println("包含pdf");
        }
        return type;
    }
}
